package api;

import cn.hutool.json.JSONUtil;
import util.AppVar;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author shkstart
 * 退出，删除session
 * @create 2023-01-13-12:03
 */
@WebServlet("/loginout")
public class LoginOutServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //在这里关闭session

        //首先得到前端的session,参数设置时，除了登录使使用true,其他都使用false
        HttpSession session = req.getSession(false);
        if(session!=null && session.getAttribute(AppVar.SESSION_USERINFO_KEY)!=null){
            //说明此时正处于登录状态，清空session
            session.setAttribute(AppVar.SESSION_USERINFO_KEY,null);
        }
        //将结果返回给前端
        resp.setContentType(AppVar.RESP_JSON_UTF8);
        resp.getWriter().println(
                JSONUtil.toJsonStr(
                        ResultUtils.toResult(200,1,null)
                )
        );
    }
}
